package cn.zhang.reimbursement_1.service.impl;

import cn.zhang.reimbursement_1.config.LoginInterceptor;
import cn.zhang.reimbursement_1.mapper.RecordMapper;
import cn.zhang.reimbursement_1.model.Record;
import cn.zhang.reimbursement_1.request.LoginRequest;
import cn.zhang.reimbursement_1.request.UserRequest;
import cn.zhang.reimbursement_1.tools.JWTUtil;
import cn.zhang.reimbursement_1.tools.JsonData;
import cn.zhang.reimbursement_1.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zhang.reimbursement_1.model.User;
import cn.zhang.reimbursement_1.service.UserService;
import cn.zhang.reimbursement_1.mapper.UserMapper;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.soap.SOAPBinding;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zfs90
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2022-02-27 14:14:07
*/
@Service
public class UserServiceImpl  implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RecordMapper recordMapper;


    /**
     * 添加用户
     * @param userRequest
     * @return
     */
    @Override
    public JsonData saveUser(UserRequest userRequest) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if(userRequest==null){
            return JsonData.buildCodeAndMsg(-1,"login对象不可为空");
        }
        User user1 = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getUsername,userRequest.getUsername()));
        if (user1!=null){
            return JsonData.buildCodeAndMsg(-1,"用户已存在请勿重复添加!");
        }
        String phone = userRequest.getPhone();
        if (phone.length()<11 && phone.indexOf(0)!=1){
            return JsonData.buildCodeAndMsg(-1,"手机号格式错误");
        }
        String pwd  = String.valueOf(new SimpleHash("MD5","000000",userRequest.getUsername(),1024));
        User user = new User();
        BeanUtils.copyProperties(userRequest,user);
        user.setPassword(pwd);
        user.setType(1);


        //执行插入
        if(loginRequest.getRolename().equals("管理员")){
            int insert = userMapper.insert(user);
            if(insert!=0){
                return JsonData.buildSuccess();
            }
        }else {
            return JsonData.buildCodeAndMsg(-1,"非法访问，已记录日志");
        }


        return JsonData.buildCodeAndMsg(-1,"用户添加失败，联系后端");
    }

    /**
     * 登录接口
     * @param loginRequest
     * @return
     */
    @Override
    public JsonData login(LoginRequest loginRequest) {
        String pwd = String.valueOf(new SimpleHash("MD5",loginRequest.getPassword(),loginRequest.getUsername(),1024));
        if(loginRequest.getUsername()==null||loginRequest.getPassword()==null){
            return JsonData.buildCodeAndMsg(-1,"登录对象不可为空");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .lambda()
                .eq(User::getUsername,loginRequest.getUsername())
                .eq(User::getPassword,pwd));
        if(user==null){
            return JsonData.buildCodeAndMsg(-1,"账号或密码错误");
        }
        if(user.getType()==0){
            return JsonData.buildCodeAndMsg(-1,"账号未激活，请联系管理员");
        }

        LoginRequest loginRequest1 = new LoginRequest();
        loginRequest1.setRolename(user.getRolename());
        loginRequest1.setUsername(user.getUsername());
        loginRequest1.setId(user.getId());
        String token = JWTUtil.geneJsonWebToken(loginRequest1);
        return JsonData.buildSuccess(token);
    }

    /**
     * 分页查询根据姓名，部门编号，角色进行模糊查询
     * @param pageNum
     * @param pageSize
     * @param likeUser
     * @return
     */
    @Override
    public JsonData pageUser(int pageNum, int pageSize, String likeUser) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum,pageSize)
                , Wrappers.<User>lambdaQuery()
                        .like(User::getRolename,likeUser).or()
                        .like(User::getTruename,likeUser).or()
                        .like(User::getClassNo,likeUser).orderByDesc(User::getId));
        Map<String,Object> userMap = new HashMap<>(3);
        userMap.put("total_pages",userPage.getPages());
        userMap.put("total_record",userPage.getTotal());
        userMap.put("records_data",userPage.getRecords().stream().map(obj->{
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(obj,userVO);
            return userVO;
        }).collect(Collectors.toList()));
        if (loginRequest.getRolename().equals("管理员")||loginRequest.getRolename().equals("经理")){
            return JsonData.buildSuccess(userMap);
        }
        return JsonData.buildCodeAndMsg(-1,"权限不足！");
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public JsonData updateUser(UserVO user) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if (user==null){
            return JsonData.buildCodeAndMsg(-1,"修改用户对象为空");
        }

        User user1 = userMapper.selectById(user.getId());
        BeanUtils.copyProperties(user,user1);
        if (loginRequest.getRolename().equals("管理员")){
            userMapper.updateById(user1);
        }else {
            return JsonData.buildCodeAndMsg(-1,"没有权限");
        }

        Record record = new Record();
        record.setRealname(loginRequest.getUsername());
        record.setOperation("修改");
        record.setInsertTime(new Date());
        record.setDetails("修改了"+user1.getTruename());
        recordMapper.insert(record);


        return JsonData.buildSuccess();
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Override
    public JsonData delUser(Integer userId) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        if (userId==0){
            return JsonData.buildCodeAndMsg(-1,"删除对象为空");
        }
        User user = userMapper.selectById(userId);
        if (loginRequest.getRolename().equals("管理员")){
            userMapper.deleteById(userId);
        }else {
            return JsonData.buildCodeAndMsg(-1,"没有权限");
        }

        Record record = new Record();
        record.setRealname(loginRequest.getUsername());
        record.setOperation("删除");
        record.setInsertTime(new Date());
        record.setDetails("删除了"+user.getTruename());
        recordMapper.insert(record);

        return JsonData.buildSuccess();
    }

    /**
     * 修改密码
     * @return
     */
    @Override
    public JsonData updatePwd(String pwd) {
        LoginRequest loginRequest = LoginInterceptor.loginThreadLocal.get();
        User user = userMapper.selectById(loginRequest.getId());
        String nwePwd = String.valueOf(new SimpleHash("MD5",pwd,user.getUsername(),1024));
        user.setPassword(nwePwd);
        if (loginRequest.getUsername().equals(user.getUsername())){
            userMapper.updateById(user);
        }
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData getDatile() {
        LoginRequest loginRequest  = LoginInterceptor.loginThreadLocal.get();
        User user = userMapper.selectById(loginRequest.getId());
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return JsonData.buildSuccess(userVO);
    }

    /**
     * 得到全部用户
     * @return
     */
    @Override
    public JsonData getAll() {
        List<User> userList = userMapper.selectList(new QueryWrapper<User>());
        List<UserVO> userVOS = userList.stream().map(obj -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(obj, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return JsonData.buildSuccess(userVOS);
    }
}




